package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dto.OrderSettingDTO;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrdersettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description 预约设置控制器
 */
@Slf4j
@RestController
@RequestMapping("ordersetting")
public class OrdersettingController {

    /**
     *  注入预约设置业务层对象
     */
    @Autowired
    private OrdersettingService ordersettingService;

    /**
     * ⽂件上传批量进⾏预约设置
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        log.info("⽂件上传批量进⾏预约设置");
        // 获取文件名
        String filename = excelFile.getOriginalFilename();
        if(StringUtils.isEmpty(filename)){
            return new Result(false,"缺少文件名");
        }

        //1 根据类型创建Workbook
        Workbook workbook = null;
        try (InputStream is = excelFile.getInputStream();) {
            //1.1构造workbook
            if(filename.endsWith(".xls")){
                // excel 2003
                workbook = new HSSFWorkbook(is);
            }else if(filename.endsWith(".xlsx")){
                // excel 2007
                workbook = new XSSFWorkbook(is);
            }else{
                return new Result(false,"文件格式不正确，请检查重试");
            }
        } catch (IOException e) {
            log.error("",e);
            return new Result(false, "文件上传失败");
        }
        //1.2遍历取数据
        List<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet sheet : workbook) {
            // 第0行为表头，直接从第1行取
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //获取行
                Row row = sheet.getRow(i);
                //解析行
                OrderSetting orderSetting = parseOrderSetting(row);
                //加入列表
                orderSettings.add(orderSetting);
            }
        }
        log.info("[预约设置-上传]解析成功,result:{}",orderSettings);

        //2 通用service
        ordersettingService.upload(orderSettings);

        return new Result(true,MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 体检预约-基于⽇历实现预约设置
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        log.info("体检预约-基于⽇历实现预约设置");
        ordersettingService.editNumberByDate(orderSetting);
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    /**
     *  ⽇历展示预约设置信息
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String year,String month){
        log.info("[预约设置-展示预约设置信息]year:{},month:{}",year,month);
        // 调用service层方法
        List<OrderSettingDTO> orderSettingList =  this.ordersettingService.getOrderSettingByMonth(year,month);
        // 响应数据
        return new Result(true, MessageConst.QUERY_ORDER_SUCCESS,orderSettingList);
    }

    /**
     * 获取每行数据
     * @param row 行数
     * @return
     */
    private OrderSetting parseOrderSetting(Row row){
        Date date = null;
        Integer number = null;
        try {
            //获取日期
            if(null != row.getCell(0) ){
                //如果单元格没有数据，则getDateCellValue返回null
                date = row.getCell(0).getDateCellValue();
            }
            //获取最大预约数量
            if(null != row.getCell(1)){
                //如果单元格没有数据，则getNumericCellValue返回0
                double numberValue = row.getCell(1).getNumericCellValue();
                //将double型转为int型
                number =  Double.valueOf(numberValue).intValue();
            }
        }catch (IllegalStateException|NumberFormatException e){
            log.error("",e);
            throw new BusinessRuntimeException(String.format("数据格式错误,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        // 判断是否缺少数据
        if(null == date || null == number){
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }
        return new OrderSetting(date,number);
    }
}
